package com.atguigu.serviceedu.service.impl;

import com.atguigu.service.handler.GuliException;
import com.atguigu.serviceedu.entity.EduChapter;
import com.atguigu.serviceedu.entity.EduVideo;
import com.atguigu.serviceedu.entity.chapter.ChapterVo;
import com.atguigu.serviceedu.entity.chapter.VideoVo;
import com.atguigu.serviceedu.entity.vo.CourseInfoVo;
import com.atguigu.serviceedu.mapper.EduChapterMapper;
import com.atguigu.serviceedu.service.EduChapterService;
import com.atguigu.serviceedu.service.EduVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-08-29
 */
@Service
public class EduChapterServiceImpl extends ServiceImpl<EduChapterMapper, EduChapter> implements EduChapterService {
    @Autowired
    private EduVideoService videoService;
    @Override
    public List<ChapterVo> getAllChaptersByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapperChapter=new QueryWrapper<>();
        wrapperChapter.eq("course_id",courseId);
        List<EduChapter> chapters= baseMapper.selectList(wrapperChapter);
        QueryWrapper<EduVideo> wrapperVideo=new QueryWrapper<>();
        wrapperVideo.eq("course_id",courseId);
        List<EduVideo> videos= videoService.list(wrapperVideo);
        List<ChapterVo> chapterVos=new ArrayList<>();
        for(int i=0;i<chapters.size();i++){
            ChapterVo chapterVo=new ChapterVo();
            EduChapter eduChapter=chapters.get(i);
            BeanUtils.copyProperties(eduChapter,chapterVo);
            for(int j=0;j<videos.size();j++){
                if(chapterVo.getId().equals(videos.get(j).getChapterId())){
                    VideoVo videoVo=new VideoVo();
                    BeanUtils.copyProperties(videos.get(j),videoVo);
                    chapterVo.getChildren().add(videoVo);
                }
            }
            chapterVos.add(chapterVo);
        }
        return chapterVos;
    }

    @Override
    public boolean deleteChapterById(String id) {
        QueryWrapper<EduVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("chapter_id", id);
        int count = videoService.count(wrapper);
        if (count > 0) {
            throw new GuliException(20001, "小节不为空，不能删除！");
        } else {
            int i = baseMapper.deleteById(id);
             return i>0;
        }
    }

    @Override
    public void removeByCourseId(String courseId) {
        QueryWrapper<EduChapter> wrapper=new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        baseMapper.delete(wrapper);
    }

}
